import { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { View, Image, Button, Input, Text } from '@tarojs/components'
import { connect } from 'react-redux'
import { AtCountdown } from 'taro-ui'
import { getMiniQrcode, qrcodeConfirm, qrCodewaitConfirm, getMiniQrcodeStore } from '@/api/pick'

import './index.scss'
interface State {
  item: object,
  realname: string,
  id: string | number,
  time: number,
  submitLoading: boolean
}

@connect<any>(({ user, car }) => ({ user, car }))
export default class Index extends Component {
  $instance = getCurrentInstance();
  lightTime: NodeJS.Timeout
  constructor (props) {
    super(props)
    this.state = {
      item: {},
      realname: '',
      id: '',
      time: 5,
      submitLoading: false
    }
  }

  state: State


  UNSAFE_componentWillMount() { }
  componentDidMount() {
    // 抽奖转盘闪烁效果

  }
  parseQueryString(url) {
    let arr = url.split('=')[1]
    return arr
  }
  UNSAFE_componentWillReceiveProps(nextProps, nextContext) { }
  componentDidShow() {
    // 获取活动id
    const { scene = "", qId } = this.$instance.router.params
    let REGISTER_DATA = Taro.getStorageSync('REGISTER_DATA') || "{}"
    if (REGISTER_DATA) {
      REGISTER_DATA = JSON.parse(REGISTER_DATA)
      REGISTER_DATA.registerType = 8 //建档扫码：扫码注册
    }
    let qrcodeId = qId
    if (scene) {
      qrcodeId = this.parseQueryString(decodeURIComponent(scene))
    }
    getMiniQrcodeStore({ id: qrcodeId }).then(res => {
      if (REGISTER_DATA) {
        REGISTER_DATA.storeCode = res.data.data.storeCode
        Taro.setStorageSync('REGISTER_DATA', JSON.stringify(REGISTER_DATA))
      }
      this.getWeRunData(qrcodeId)
    })
  }
  getWeRunData(qid) {
    getMiniQrcode({
      id: qid
    }).then(res => {
      let data = res.data.data
      this.setState({
        item: data,
        id: qid
      })
      this.handleAsync(qid)
    })
  }
  handleAsync(id) {
    this.lightTime = setInterval(() => {
      setTimeout(() => {
        qrCodewaitConfirm({ id })
      }, 0)
    }, 10000)
  }
  componentWillUnmount() {
    clearInterval(this.lightTime)
  }
  hamdleRealname(e) {
    this.setState({
      realname: e.detail.value
    })
  }


  handleSubmit() {
    let USERINFO = Taro.getStorageSync('IS_USERINFO')
    let { item, realname, submitLoading } = this.state
    console.log('realname', realname)
    if (!realname) {
      Taro.showToast({
        title: '请先填写称呼！',
        icon: 'none',
        duration: 2000,
      })
      return
    }
    //防止用户连续点击
    if (submitLoading) return
    this.setState({
      submitLoading: true
    })
    Taro.showLoading({ title: '提交中' })
    qrcodeConfirm({
      id: item.id,
      mobile: USERINFO.mobile,
      realname: realname
    }).then(res => {
      Taro.hideLoading()
      let data = res.data.data
      let { status, qrcode } = data
      item = qrcode
      Taro.setNavigationBarTitle({
        title: '提交结果'
      })
      if (status == 0) { // 提交失败
        item.status = 5


      } else if (status == 1) { // 提交成功
        item.status = 4
      }
      this.setState({
        item,
        submitLoading: false
      })
    })

  }
  gotoIndex() {
    Taro.switchTab({
      url: '/pages/tabbar/index/index'
    })
  }
  onTimeUp() {
    this.gotoIndex()
  }

  render() {
    const { item, realname } = this.state;
    const USERINFO = Taro.getStorageSync('IS_USERINFO')
    let mobile = USERINFO.mobile
    if (USERINFO) {
      var reg = /(\d{3})\d{4}(\d{4})/;
      var newmobile = USERINFO.mobile.replace(reg, "$1******$2")
      mobile = newmobile
    }
    if (item.mobile) {
      var reg = /(\d{3})\d{4}(\d{4})/;
      var newmobile = item.mobile.replace(reg, "$1******$2")
      item.mobile = newmobile
    }
    return (
      <View className="pick" >
        <official-account></official-account>
        {
          item.status == 1 || item.status == 2 ? <View>
            <Image src='https://static3.jekunauto.com/img/pick/pick_banner.png' className='pick-img'></Image>
            <View className='pick-info'>
              <View className='pick-car'>{item.carLicense}</View>
              <View className='pick-sub'>请确认手机号是否正确，若有误请联系门店更改。</View>

              <View className='pick-line'>
                <View className='key'>您的账号</View>
                <View className='val'>{mobile}</View>
              </View>
              <View className='pick-line'>
                <View className='key'>建档门店</View>
                <View className='val'>{item.storeName}</View>
              </View>
              <View className='pick-line'>
                <View className='key'>您的称呼</View>
                <View className='val'>

                  <Input placeholder='可以告诉门店怎么称呼您' value={realname} onInput={(e) => this.hamdleRealname(e)} className='name-inp'></Input>
                </View>
              </View>

              <View className='pick-tips'>
                <View className='tips-head'><Text className='info-ico'></Text>温馨提示</View>
                <View className='tips-txt'>为了给您的车辆提供更好的服务，本次提交仅用作与门店建立车辆信息档案使用。</View>
              </View>

              <View className='pick-btn' onClick={() => this.handleSubmit()}>确认提交</View>

            </View>
          </View> : null
        }

        {
          item.status == 3 ? <View className=''>
            <View className='result-warp'>
              <Image src="https://static3.jekunauto.com/img/pick/pick_status_fail.png" className='result-img'></Image>
              <View className='result-title'>车辆可能已经建档</View>
              <View className='result-txt'>请跟门店确认手机号是否正确</View>
            </View>
            <View className='result-info'>
              <View className='pick-line'>
                <View className='key'>车牌号</View>
                <View className='val'>{item.carLicense}</View>
              </View>
              <View className='pick-line'>
                <View className='key'>手机号</View>
                <View className='val'>{item.mobile}</View>
              </View>
            </View>
            <View className='result-btn' onClick={() => this.gotoIndex()}>
              去养车商城
            </View>
          </View> : null
        }

        {
          item.status == 4 ? <View className=''>
            <View className='result-warp'>
              <Image src="https://static3.jekunauto.com/img/pick/pick_success.png" className='result-img-1'></Image>
              <View className='result-title'>提交成功</View>
              <View className='result-txt'>为爱车开启养护新体验</View>
            </View>

            <View className='result-info'>
              <View className='pick-line'>
                <View className='key'>车牌号</View>
                <View className='val'>{item.carLicense}</View>
              </View>
              <View className='pick-line'>
                <View className='key'>手机号</View>
                <View className='val'>{mobile}</View>
              </View>
            </View>

            <View className='result-btn mt194'>
              即将跳转养车商城 ({<AtCountdown
                isShowHour={false}
                onTimeUp={() => this.onTimeUp()}
                format={{ seconds: '' }}
                seconds={5}
              />})
            </View>
          </View> : null
        }


        {
          item.status == 5 ? <View className=''>
            <View className='result-warp'>
              <Image src="https://static3.jekunauto.com/img/pick/pick_fail.png.png" className='result-img-1'></Image>
              <View className='result-title'>提交失败</View>
              <View className='result-txt'>
                <View>该链接可能已经被建过档</View>
                <View>请跟门店确认手机号是否正确</View>
              </View>
              <View className='result-info'>
                <View className='pick-line'>
                  <View className='key'>车牌号</View>
                  <View className='val'>{item.carLicense}</View>
                </View>
                <View className='pick-line'>
                  <View className='key'>手机号</View>
                  <View className='val'>{item.mobile}</View>
                </View>
              </View>
            </View>

            <View className='result-btn mt194' onClick={() => this.gotoIndex()}>
              去养车商城
            </View>
          </View> : null
        }

      </View>
    )
  }
}
